package com.cssw.fyzb.busi.api.live;

import com.cssw.fyzb.busi.config.TpsClient;
import com.cssw.fyzb.busi.model.tps.OptLiveStream;
import com.cssw.fyzb.busi.service.live.LiveService;
import com.cssw.fyzb.core.model.dodb.CmfLive;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.cssw.fyzb.busi.util.Bizs.ERROR_LIVE_UNKNOWN_ROOM;

/**
 * @author Feng Chen
 */
@Function(description = "创建混流", parameters = {
        @Parameter(name = "liveId", type = Type.Integer, description = "直播间编号", required = true),
        @Parameter(name = "params", type = Type.String, description = "参数", required = true),
})
@Component
public class CreateMixLive implements Action {

    @Autowired
    private TpsClient tpsClient;

    @Autowired
    private LiveService liveService;

    private static final Logger logger = LoggerFactory.getLogger(CreateMixLive.class);

    @Override
    public Response execute(Request request) throws Exception {
        Long liveId = request.getLong("liveId");
        String params = request.getString("params");

        try {

            // 查询直播间
            CmfLive live = liveService.findByLiveId(liveId);

            if (live == null) {
                return Response.fail(ERROR_LIVE_UNKNOWN_ROOM.message, ERROR_LIVE_UNKNOWN_ROOM.code);
            }

            OptLiveStream opt = tpsClient.createMixLiveStream(String.valueOf(liveId), String.valueOf(live.getAnchorId()), params);
            if (opt.getErrCode() == null) {
                return Response.success();
            } else {
                logger.error("createMixLiveStream error, cause: errcode {}, errMsg {}", opt.getErrCode(), opt.getErrMsg());
                return Response.fail("操作异常");
            }

        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("操作异常");
        }

    }

}
